package cn.tedu.xxmall.security;

import cn.tedu.xxmall.mapper.AdminMapper;
import cn.tedu.xxmall.pojo.vo.AdminLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author : Jimmy
 * @date : 2022-08-25 20:17
 **/
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("根据用户名【{}】从数据库查询用户信息……", s);
        AdminLoginVO adminLoginVO = adminMapper.selectByUserName(s);
        if (adminLoginVO ==null){
            String message = "登录失败，用户名不存在！";
            log.warn(message);
            throw new UsernameNotFoundException(message);
        }
        log.debug("{}",adminLoginVO);
        List<String> permissions = adminLoginVO.getPermissions();

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        AdminDetail userDetails = new AdminDetail(adminLoginVO.getUsername(),adminLoginVO.getPassword(),
                adminLoginVO.getEnable()==1,authorities);
        userDetails.setId(adminLoginVO.getId());
        return userDetails;
    }
}
